package com.zhou.widget;

import java.util.Arrays;

import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.zhou.server.WifiHelper;

/**
 * @author : zhou <zhengzhou.xu@hotmail.com> description : Widget
 */
public class WidgetProvider extends AppWidgetProvider {

    private static final String TAG = "ExampleAppWidgetProvider";

    // 启动ExampleAppWidgetService服务对应的action
    private static final Intent EXAMPLE_SERVICE_INTENT =
            new Intent("android.appwidget.action.EXAMPLE_APP_WIDGET_SERVICE");
    // 更新 widget 的广播对应的action
    private static final String ACTION_UPDATE_ALL = "com.zhou.widget.UPDATE_ALL";
    private static final String ACTION_CLICK = "com.zhou.widget.click";

    private int[] appWidgetIds;

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // onUpdate() 在更新 widget 时，被执行，
        Log.d(TAG, "onUpdate(): appWidgetIds=" + Arrays.toString(appWidgetIds));
        updateAllAppWidgets(context, appWidgetManager, appWidgetIds);
    }

    // 当 widget 被初次添加 或者 当 widget 的大小被改变时，被调用
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
        Log.d(TAG, "onAppWidgetOptionsChanged");
        super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
    }

    // widget被删除时调用
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
    }

    // 第一个widget被创建时调用
    @Override
    public void onEnabled(Context context) {
        Log.d(TAG, "onEnabled");
        super.onEnabled(context);
    }

    // 最后一个widget被删除时调用
    @Override
    public void onDisabled(Context context) {
        Log.d(TAG, "onDisabled");
        super.onDisabled(context);
    }

    // 接收广播的回调函数
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        Log.i(TAG, "this instants: " + this.hashCode());
        Log.i(TAG, "OnReceive:Action: " + action);
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

        Bundle extras = intent.getExtras();
        if (extras != null) {
            appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS);
        }
        appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, WidgetProvider.class));
        Log.d(TAG, "OnReceive:  appWidgetIds: " + Arrays.toString(appWidgetIds));

        // android.appwidget.action.APPWIDGET_UPDATE
        if (ACTION_UPDATE_ALL.equals(action) || "android.appwidget.action.APPWIDGET_UPDATE".equals(action)) {
            // “更新”广播
            updateAllAppWidgets(context, appWidgetManager, appWidgetIds);
        } else if(ACTION_CLICK.equals(action)){
            Uri uri = intent.getData();
            Log.i(TAG, "uri:" + uri.getSchemeSpecificPart());
            int id = Integer.parseInt(uri.getSchemeSpecificPart());
            dispatcherEvent(id, context);
        }
        super.onReceive(context, intent);
    }

    private void updateAllAppWidgets(Context context, AppWidgetManager appWidgetManager, int[] set) {
        if (set != null) {
            // 获取 example_appwidget.xml 对应的RemoteViews
            RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.example_appwidget);
            // 设置点击按钮对应的PendingIntent：即点击按钮时，发送广播。
            remoteView.setOnClickPendingIntent(R.id.btn_update, getPendingIntent(context, R.id.btn_update));
            remoteView.setOnClickPendingIntent(R.id.btn_app, getPendingIntent(context, R.id.btn_app));
            remoteView.setOnClickPendingIntent(R.id.btn_debug, getPendingIntent(context, R.id.btn_debug));
            remoteView.setTextViewText(R.id.name_text, "WiFi: " + WifiHelper.getWifiName(context));
            remoteView.setTextViewText(R.id.ip_text, "IP: " + WifiHelper.wifiIpAddress(context));
            // 更新 widget
            appWidgetManager.updateAppWidget(set, remoteView);
        }
    }


    private void dispatcherEvent(int id, Context context){
        switch (id) {
            case R.id.btn_debug:
                gotoDebug(context);
                break;
            case R.id.btn_app:
                gotoApp(context);
                break;
            case R.id.btn_update:
                updateIpInfo(context, appWidgetIds);
            default:
                break;
        }
    }

    private void updateIpInfo(Context context, int[] set){
        // 获取 example_appwidget.xml 对应的RemoteViews
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.example_appwidget);
        remoteView.setTextViewText(R.id.name_text, "WiFi: " + WifiHelper.getWifiName(context));
        remoteView.setTextViewText(R.id.ip_text, "IP: " + WifiHelper.wifiIpAddress(context));
        Toast.makeText(context, WifiHelper.getWifiName(context) + ":" + WifiHelper.wifiIpAddress(context), Toast.LENGTH_SHORT).show();
        // 更新 widget
        appWidgetManager.updateAppWidget(set, remoteView);
    }

    void gotoDebug(Context context){
        // android.settings.APPLICATION_DEVELOPMENT_SETTINGS
        Intent i = new Intent("com.android.settings.APPLICATION_DEVELOPMENT_SETTINGS");
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }

    private void gotoApp(Context context){
        Intent i = new Intent("android.settings.MANAGE_APPLICATIONS_SETTINGS");
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }

    private PendingIntent getPendingIntent(Context context, int btnId){
        Intent intent = new Intent(ACTION_CLICK); // ACTION_USB_CLICK
        intent.setData(Uri.parse("button:" + btnId));
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
        return pi;
    }

}
